package com.gmsk.pocket.controller;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gmsk.pocket.dao.DocFileMapper;
import com.gmsk.pocket.entity.Doc;
import com.gmsk.pocket.entity.DocFile;
import com.gmsk.pocket.entity.TableWrapper;
import com.gmsk.pocket.indexing.DocFileRepository;
import com.gmsk.pocket.service.DocFileService;
import com.gmsk.pocket.service.DocService;
import com.gmsk.pocket.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("doc")
public class DocController {

    @Autowired
    DocFileService docFileService;

    @Autowired
    DocFileRepository docFileRepository;

    @Autowired
    DocService docService;

    @RequestMapping(value = "save", method = RequestMethod.POST)
    public R save(@RequestBody  Doc doc) {
        doc.setUploadTime(new Date());
        doc.setUploadUser(1000);
        try {
            docService.insert(doc);
            for (Integer id: doc.getDocIds()) {
                DocFile docFile = docFileService.select(id);
                docFile.setDocId(doc.getId());
                docFileService.update(docFile);
                docFileRepository.save(docFile);
            }
            return R.ok();
        }catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public TableWrapper<List<Doc>> list(Integer typeId, Integer page, Integer limit) {
        try {
            if (page == null || page < 0) page = 1;
            if (limit == null || limit < 0) limit = 10;
            List<Doc> docs = docService.selectByType(typeId, (page - 1)  * limit, limit);
            Integer size = docService.selectCount(typeId);
           return new TableWrapper<>(TableWrapper.OK, size, "", docs);
        }catch (Exception e) {
            e.printStackTrace();
            return new TableWrapper<>(TableWrapper.ERROR, 0, "", null);
        }
    }

//
//    @RequestMapping("/searchDoc")
//    @ResponseBody
//    public TableWrapper<List<Doc>> searchDoc(String paramsJson, Integer page, Integer limit) {
//        TableWrapper dataWrapper = null;
//        Map params = JSON.parseObject(paramsJson, Map.class);
//        try {
//            DocService.Result docResult =docService.searchDoc(params,page-1,limit);
//            dataWrapper = new TableWrapper(TableWrapper.OK, docResult.getSize().intValue() , "OK", docResult.getDocList());
//            return dataWrapper;
//        }catch (Exception e) {
//            e.printStackTrace();
//            dataWrapper = new TableWrapper(TableWrapper.ERROR, 0, "搜索失败", null);
//        }
//        return dataWrapper;
//    }



}
